import { Input, message, Form } from "antd";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import "./index.scss";
import { useForm } from "antd/es/form/Form";
import FormItem from "antd/es/form/FormItem";
import { login } from "@/api/user";

const Login = () => {
  const [isLogin, setIsLogin] = useState(true);
  const [form] = useForm();
  const navigate = useNavigate();
  const loginHandle = async () => {
    const params = form.getFieldsValue();
    login(params).then((res) => {
      const { avatarUrl, nickname, phone, roleType, _id } = res.userInfo;
      sessionStorage.setItem("token", res.token);
      sessionStorage.setItem("nickname", nickname);
      sessionStorage.setItem("phone", phone);
      sessionStorage.setItem("userID", String(_id));
      sessionStorage.setItem("avatarUrl", avatarUrl);
      navigate("/home");
    });
  };
  const registerHandle = async () => {};
  const handleSubmit = () => {
    (isLogin && loginHandle()) || registerHandle();
  };
  return (
    <div className="login_container">
      <Form form={form}>
        <div id="login_box" style={{ height: isLogin ? "400px" : "500px" }}>
          <h2 style={{ color: "#fff" }}>{isLogin ? "LOGIN" : "REGSITER"}</h2>
          <div className="input_box">
            <FormItem
              name="phone"
              rules={[
                {
                  required: true,
                  message: "请输入手机号码",
                },
                {
                  pattern: /^1[3456789]\d{9}$/,
                  message: "请输入正确的手机号码",
                },
              ]}
            >
              <Input type="text" placeholder="请输入用户名" />
            </FormItem>
          </div>
          {!isLogin && (
            <div className="input_box">
              <FormItem
                name="nickname"
                rules={[
                  {
                    required: true,
                    message: "请输入昵称",
                  },
                ]}
              >
                <Input type="password" placeholder="请输入昵称" />
              </FormItem>
            </div>
          )}
          <div className="input_box">
            <FormItem
              name="password"
              rules={[
                {
                  required: true,
                  message: "请输入密码",
                },
                {
                  min: 6,
                  message: "密码长度不能短于6位",
                },
              ]}
            >
              <Input type="password" placeholder="请输入密码" />
            </FormItem>
          </div>
          <button onClick={handleSubmit}>{isLogin ? "登录" : "注册"}</button>
          <span className="tips" onClick={() => setIsLogin(!isLogin)}>
            {isLogin ? "没账号？快去注册 >" : "立即登录 >"}
          </span>
        </div>
      </Form>
    </div>
  );
};

export default Login;
